package com.blast.cn

import com.wxl.common.base.AbsActivity
import com.wxl.common.serialport.*
import com.wxl.common.util.Loog
import kotlinx.android.synthetic.main.activity_main.*
import skin.support.SkinCompatManager

class MainActivity : AbsActivity() {

    var nightMode = false

    var mCurrentCollectorNum = 0

    var mDetonatorTotalNum = 0

    val sf = StringBuffer()

    override fun getCreateContentViewId(): Int {
        return R.layout.activity_main
    }

    override fun onCreateViewChanged() {

        SerialPortManager.open()

        /**
         * 插入采集器
         */
        Serials.registerSingleSerial(SerialCode.CODE_COLLECTOR_INSERT, object : Serial() {
            override fun loadReceiveData(data: String) {
                mainTextView.text = data
                SerialPortManager.send(SerialCmd.CODE_READ_COLLECTOR_INFO)
            }
        })

        mainTextView.setOnClickListener {
            if(!nightMode) {
                SkinCompatManager.getInstance()
                    .loadSkin("night", null, SkinCompatManager.SKIN_LOADER_STRATEGY_BUILD_IN)
            } else {
                SkinCompatManager.getInstance().restoreDefaultTheme()
            }
            nightMode = !nightMode
        }


        /**
         * 返回采集器信息
         */
        Serials.registerSingleStartHexSerial(SerialCode.CODE_COLLECTOR_INFO,object : Serial(){
            override fun loadReceiveData(data: String) {
                mDetonatorTotalNum = Integer.valueOf(data.substring(12, 16), 16)
                Loog.e("mDetonatorTotalNum:$mDetonatorTotalNum")
                sendCollectorInputData()
            }
        })

        //雷管信息
        //2307FFA030AA5F
        //2309FFA03002003123
        Serials.registerStartHexSerial(SerialCode.CODE_COLLECTOR_DETONATOR_INFO,object : Serial(){
            override fun loadReceiveData(data: String) {
                sf.append(data+"\n")
                SerialPortManager.cancelIntervalWork()
                mCurrentCollectorNum ++
                mainTextView.text = sf.toString()
                sendCollectorInputData()
            }
        })

    }


    private fun sendCollectorInputData(){
        if(mCurrentCollectorNum < mDetonatorTotalNum){
            val num = SerialUtil.getCurrentDetonatorNum(mCurrentCollectorNum)
            SerialPortManager.send(SerialCmd.CODE_INPUT_COLLECTOR_DATA+num)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        SerialPortManager.close()
    }
}
